package net.xdclass.rbac_shiro.controller;

import net.xdclass.rbac_shiro.domain.JsonData;
import net.xdclass.rbac_shiro.domain.UserQuery;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created whit IntelliJ IDEA
 * User:杨骏杰
 * Date:2021/2/15
 * Time:21:05
 */
@RestController
@RequestMapping("pub")
public class PublicController {

    @RequestMapping("index")
    public JsonData index(){
        List<String> videoList = new ArrayList<>();
        videoList.add("Mysql零基础入门到实战 数据库教程");
        videoList.add("Redis高并发高可用集群百万级秒杀实战");
        videoList.add("Zookeeper+Dubbo视频教程 微服务教程分布式教程");
        videoList.add("2019年新版本RocketMQ4.X教程消息队列教程");
        videoList.add("微服务SpringCloud+Docker入门到高级实战");

        return JsonData.buildSuccess(videoList);
    }

    /**
     * 需要登陆却没有登陆，则使用此接口
     * ShiroFilterFactoryBean()再过滤器中配置未登录接口
     * @return
     */
    @RequestMapping("need_login")
    public JsonData needLogin(){
        return JsonData.buildSuccess("温馨提示：请使用对应的账号登陆",-2);
    }

    /**
     * 登陆了，但是需要权限却没有权限，则使用此接口
     * ShiroFilterFactoryBean()再过滤器中配置登陆却没有权限的接口
     * @return
     */
    @RequestMapping("not_permit")
    public JsonData notpermit(){
        return JsonData.buildSuccess("温馨提示：拒绝访问，没权限",-3);
    }

    /**
     * 登陆接口
     * @param userQuery
     * @param request
     * @param response
     * @return
     */
    @PostMapping("login")
    public JsonData login(@RequestBody UserQuery userQuery, HttpServletRequest request, HttpServletResponse response){
        //得到shiroSubject的操作主体
        Subject subject = SecurityUtils.getSubject();
        Map<String ,Object> info  = new HashMap<>();
        try {
            //把用户传递账号和密码封装成usernamePasswordToken
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userQuery.getName(), userQuery.getPwd());

            //认证
            subject.login(usernamePasswordToken);

            info.put("msg","登陆成功");
            info.put("session_id",subject.getSession().getId());

            return JsonData.buildSuccess(info);
        }catch (Exception e){
            e.getStackTrace();
            info.put("msg","账号和密码错误");
            return JsonData.buildSuccess(info);
        }
     }
}
